//
//  NSFileManager+Extension.m
//  BSBuDeJie
//
//  Created by monkey on 2018/12/18.
//  Copyright © 2018 itcast. All rights reserved.
//

#import "NSFileManager+Extension.h"

@implementation NSFileManager (Extension)

+ (void)getFileSize:(NSString *)filePath completion:(void (^)(NSUInteger fileSize))completion;
{
    NSFileManager *fileManager = [self defaultManager];
    
    /* 如果传入的文件路径不存在 返回-1
     如果传入的是一个文件 返回文件大小
     如果传入到的是一个文件夹 计算文件夹内所有的文件大小
     */
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSUInteger fileSize = 0;
        BOOL isDirectory = false;
        BOOL isExists = [fileManager fileExistsAtPath:filePath isDirectory: &isDirectory];
        
        if (!isExists) {
            // 文件不存在
            fileSize = -1;
        } else if (!isDirectory) {
            // 传入的是一个文件
            NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath error:nil];
            fileSize = [attributes[NSFileSize] integerValue];
        } else {
            // 传入的是一个文件夹
            NSArray *subPaths = [fileManager subpathsAtPath:filePath];
            for (NSString *subPath in subPaths) {
                // 拼接完整路径
                NSString *fullPath = [filePath stringByAppendingPathComponent:subPath];
                [fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
                if (isDirectory) {
                    continue;
                } else {
                    NSDictionary *attributes = [fileManager attributesOfItemAtPath:fullPath error:nil];
                    fileSize += [attributes[NSFileSize] integerValue];
                }
            }
        }
        
        completion(fileSize);
    });
}

+ (void)removeFilePath:(NSString *)filePath completion:(void (^)(NSError * _Nullable))completion
{
    
    NSFileManager *fileManager = [self defaultManager];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        BOOL isDirectory = false;
        BOOL isExists = [fileManager fileExistsAtPath:filePath isDirectory: &isDirectory];
        if (!isExists) {
            // 文件不存在
            completion([NSError errorWithDomain:@"error" code:100001 userInfo:@{@"reason" : @"要删除的路径不存在"}]);
        } else if (!isDirectory) {
            // 传入的是一个文件
            [fileManager removeItemAtPath:filePath error:nil];
            completion(nil);
        } else {
            // 获取当前目录下的子目录 仅一级 不包括子目录的子目录
            NSArray *subItems = [fileManager contentsOfDirectoryAtPath:filePath error:nil];
            for (NSString *subItem in subItems) {
                NSString *fullPath = [filePath stringByAppendingPathComponent:subItem];
                [fileManager removeItemAtPath:fullPath error:nil];
            }
        }
        
        completion(nil);
    });
    
}

@end
